package com.langshixiaobai.api;


import com.langshixiaobai.eneity.User;
import com.langshixiaobai.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserApi {

    @Autowired
    private UserMapper userMapper;


    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        //先从数据库获取
        User user = userMapper.selectUser(username);
        //验证
        if (user == null || !user.getPassword().equals(password)) {
            //登入失败
            System.out.println("登入失败");
            return new User();
        }
        //如果当前没有会话，则创建一个（true）
        HttpSession session = req.getSession(true);
        //将数据存入当前会话，方便后续拿到
        session.setAttribute("user", user);

        return user;

    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        try {
            //存入信息
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insertUser(user);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            //当出现异常时，代表filed value重复，返回空对象，告诉前端注册失败
            return new User();
        }
    }

    @RequestMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        try {
            //如果没有会话则不会创建，而是返回null
            HttpSession session = req.getSession(false);
            //从会话中你获取信息，如果没有会话session=null，则会空指针
            //通过捕获异常，来判断当前用户是否已经登入
            User user = (User) session.getAttribute("user");
            //将新消息返回
            User newUser = userMapper.selectUser(user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            //当前没有会话，没有用户信息，需要去登入创建会话
            return new User();
        }
    }
}
